#Implement views to handle API requests for statistics.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import KnowledgeBaseVisit
from .serializers import KnowledgeBaseVisitSerializer
from django.db.models import Sum


from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import APIAccessLog
from .serializers import APIAccessLogSerializer
from django.db.models import Count

class VisitStatisticsAPIView(APIView):
    def get(self, request):
        # Query parameters: start_date, end_date, client_type, knowledge_base
        start_date = request.query_params.get('start_date')
        end_date = request.query_params.get('end_date')
        client_type = request.query_params.get('client_type')
        knowledge_base = request.query_params.get('knowledge_base')
        
        # Filter visits based on query params
        filters = {}
        if start_date and end_date:
            filters['timestamp__range'] = [start_date, end_date]
        if client_type:
            filters['client_type'] = client_type
        if knowledge_base:
            filters['knowledge_base'] = knowledge_base
        
        visits = KnowledgeBaseVisit.objects.filter(**filters)
        
        # Aggregate data
        total_visits = visits.aggregate(total=Sum('visit_count'))['total'] or 0
        data = {
            'total_visits': total_visits,
            'details': KnowledgeBaseVisitSerializer(visits, many=True).data,
        }
        return Response(data, status=status.HTTP_200_OK)

class MyAPIView(APIView):
    def get(self, request):
        # 记录API访问
        APIAccessLog.objects.create(
            endpoint=request.path,
            ip_address=request.META.get('REMOTE_ADDR'),
            user_agent=request.META.get('HTTP_USER_AGENT', '')
        )
 # 返回访问TOP5 
        top_5_endpoints = APIAccessLog.objects.values('endpoint').annotate(count=Count('id')).order_by('-count')[:5]
        return Response({
            'message': 'API accessed successfully',
            'top_5_endpoints': top_5_endpoints
        })